Operator_Convert Method

Used to convert from one type to another, providing custom functionality.

Syntax


Notes

The following example converts to a Vector from an Integer (The Vector class is defined in Operator_Add.) The Operator_Convert method is added to the Vector class.

Sub Operator_Convert(rhs as Operator)
  Self.x=rhs
  Self.y=rhs

You use this definition of the Operator_Convert method like this:

Dim v as Vector
v = 10  //both elements of V get the value 10

Note that the New operator is not needed here. This is because the assignment operator is returning a new instance of Vector. If you were to write v= New Vector, it would create one instance of Vector but that would be overwritten by the assignment statement.

The second type of conversion is a 'to' conversion. Use this when you want to convert the class to another type. In the following example, the Vector is converted to a string that represents its square length.

Function Operator_Convert as String
   Return Str( Self.x^2 + Self.y^2)

After defining both forms of Operator_Convert, you can use them with code like this:

Dim v as Vector =10
MsgBox v

The first line invokes the data type conversion in the first example and assigns 10 to both elements of the Vector object. The second line computes the square length and returns it as a String.